package com.nine.shop.common;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.io.Serializable;

/**
 * 接口数据返回定义类
 * 作用:将需要返回给前端的数据进行包装，同时封装status和msg两个字段并JSON序列化
 * T(泛型) 为返回数据的类型
 */
@JsonSerialize
public class ServerResponse<T> implements Serializable {

    //接口返回状态
    private Integer status;
    //返回提示信息
    private String msg;
    //返回的数据
    private T data;

    //私有构造参数，不允许外部直接调用
    private ServerResponse(int status){
        this.status = status;
    }
    private ServerResponse(int status, T data){
        this.status = status;
        this.data = data;
    }
    private ServerResponse(int status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    /**
     * 根据成功与否及是否需要返回data提供的各种静态构造方法
     */
    public static <T> ServerResponse<T> createBySuccess(){
        return new ServerResponse<>(Constant.ResponseCode.SUCCESS.getCode());
    }
    public static <T> ServerResponse<T> createBySuccess(T data){
        return new ServerResponse<>(Constant.ResponseCode.SUCCESS.getCode(),data);
    }
    public static <T> ServerResponse<T> createByError(){
        return new ServerResponse<>(Constant.ResponseCode.ERROR.getCode());
    }
    public static <T> ServerResponse<T> createByError(T data){
        return new ServerResponse<>(Constant.ResponseCode.ERROR.getCode(),data);
    }
    public static <T> ServerResponse<T> createByErrorMsg(String msg){
        return new ServerResponse<>(Constant.ResponseCode.ERROR.getCode(),msg);
    }
    public static <T> ServerResponse<T> createBySuccessMsg(String msg){
        return new ServerResponse<>(Constant.ResponseCode.SUCCESS.getCode(),msg);
    }

    /**
     * getter&setter
     */
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public T getData() {
        return data;
    }
    public void setData(T data) {
        this.data = data;
    }
}
